from threading import Thread
import sys
import select
import logging

class Listen(Thread):
    def __init__(self, online, cl, client):
        Thread.__init__(self)
        self.online = online
        self.cl = cl

        if client.xmpp_connect():
            print "Connected !"
        else:
            sys.stderr.write("Could not connect to server (maybe your password is incorrect)\n")
            sys.exit(1)

        cl.sendInitPresence(requestRoster=0)
        cl.sendPresence(typ="available", requestRoster=1)

        self.start()

    def run(self):
        socketlist = {self.cl.Connection._sock:'xmpp'}
        while self.online:
            (i, o, e) = select.select(socketlist.keys(), [], [], 1)
            for each in i:
                if socketlist[each] == 'xmpp':
                    try:
                        self.cl.Process(1)
                    except ValueError, e:
                        print e
                        logging.error(e)

